修订号 1
child_process.exec(command, [options], callback)
command
{String} 将要执行的命令,用空格分隔参数options
{Object}cwd
{String} 子进程的当前工作目录env
{Object} 环境变量键值对encoding
{String} 编码(缺省为 'utf8')shell
{String} 运行命令的 shell(UNIX 上缺省为 '/bin/sh',Windows 上缺省为 'cmd.exe'。该 shell 在 UNIX 上应当接受-c
开关,在 Windows 上应当接受/s /c
开关。在 Windows 中,命令行解析应当兼容cmd.exe
。)timeout
{Number} 超时(缺省为 0)maxBuffer
{Number} 最大缓冲(缺省为 200*1024)killSignal
{String} 结束信号(缺省为 'SIGTERM')
callback
{Function} 进程结束时回调并带上输出error
{Error}stdout
{Buffer}stderr
{Buffer}
- 返回:ChildProcess 对象
在 shell 中执行一个命令并缓冲输出。
child = exec('cat *.js bad_file | wc -l',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
回调参数为 (error, stdout, stderr)
。当成功时,error
会是 null
。当遇到错误时,error
会是一个 Error
实例,并且 err.code
会是子进程的退出代码,同时 err.signal
会被设置为结束进程的信号名。
第二个可选的参数用于指定一些选项,缺省选项为:
{ encoding: 'utf8',
timeout: 0,
maxBuffer: 200*1024,
killSignal: 'SIGTERM',
cwd: null,
env: null }
如果 timeout
大于 0,则当进程运行超过 timeout
毫秒后会被终止。子进程使用 killSignal
信号结束(缺省为 'SIGTERM'
)。maxBuffer
指定了 stdout 或 stderr 所允许的最大数据量,如果超出这个值则子进程会被终止。